package com.itheima.jdbc;

import com.itheima.pojo.Library;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
import org.springframework.web.bind.annotation.Mapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@SpringJUnitConfig(locations="classpath:beans.xml")
@RestController
public class JdbcTemplateTest {

//    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Test
    public void testAdd() {
        String sql = "insert into library (id,title,number,momey) values (?,?,?,?)";
        Object[] params = {4, "资本论",3,20};
        System.out.println(jdbcTemplate);
        int rows = jdbcTemplate.update(sql, params);
        System.out.println(rows);
    }

    @Test
    public void testUpdate() {
        String sql = "update library set momey=? where id=?";
        int rows = jdbcTemplate.update(sql, 150, 1);
        System.out.println(rows);
    }

    @Test
    public void testDelete() {
        String sql = "delete from library where id=?";
        int rows = jdbcTemplate.update(sql,  4);
        System.out.println(rows);
    }

    @RequestMapping("getL")
    public Library testSelect() {
        // 暂时用这种方法，Autowired会有问题
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        JdbcTemplate jdbcTemplate1 = (JdbcTemplate)context.getBean("jdbcTemplate");
        String sql = "select * from library where id=?";
//        Library res = jdbcTemplate.queryForObject(sql,  (rs, rowNum)->{
//            Library library = new Library();
//            library.setTitle(rs.getString("title"));
//            return library;
//        },1);
        Library res = jdbcTemplate1.queryForObject(sql, new BeanPropertyRowMapper<Library>(Library.class), 1);
        System.out.println(res);
        return res;
    }

    @Test
    public void testAllSelect() {
        String sql = "select * from library";
        List<Library> res = jdbcTemplate.query(sql, new BeanPropertyRowMapper<Library>(Library.class));
        System.out.println(res);
    }
}
